package com.kaifamiao.async;

public class WithdrawTask implements Runnable {

    private Account account;
    private long amount;

    private WithdrawTask(Account account, long amount) {
        this.account = account;
        this.amount = amount;
    }

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        for ( int i = 0; i < 3; i++ ) {
            if( account.enough ) {
                System.out.printf( "%s开始取钱，当前余额为: %d\n", name, account.balance );
                Thread.yield();
                account.balance -= amount; // 取款
                account.enough = false; // 钱不够了
                Thread.yield();
                System.out.printf( "%s取钱结束，当前余额为: %d\n", name, account.balance );
                continue;
            }
            System.out.printf("余额不足，%s取钱失败\n", name);
        }
    }

    public static void launch( String name,Account account, long amount) {
        Runnable runnable = new WithdrawTask( account, amount);
        Thread t = new Thread(runnable, name);
        t.start();
    }
}
